package org.wang.chuangen.session.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * JSON方式序列化工具类
 * 序列化工具基于fastjson
 * @author 王传根
 * @date 2016-5-13上午9:29:23
 */
public class JsonTextSerialization implements Serialization{
	
	public static final String CLASS_NAME="className";
	
	public static final String DATA_NAME="data";
	
	private Charset charset=Charset.defaultCharset(); 
	
	public JsonTextSerialization(){}
	
	public JsonTextSerialization(Charset charset) {
		this.charset = charset;
	}

	@Override
	public byte[] toObjectByte(Object data) throws IOException {
		String className=data.getClass().getName();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put(CLASS_NAME,className);
		jsonObject.put(DATA_NAME,data);
		String jsonText=jsonObject.toJSONString();
		return jsonText.getBytes(charset);
	}

	@Override
	public Object parseObjectByte(byte[] data) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		if(data==null || data.length==0)return null;
		String jsonText=new String(data, charset).trim();
		if(jsonText==null || jsonText.length()==0)return null;
		JSONObject jsonData=JSON.parseObject(jsonText);
		if(jsonData==null || jsonData.size()==0)return null;
		Object dataObject=jsonData.get(DATA_NAME);
		if(dataObject instanceof JSONArray){
			String className=jsonData.getString(CLASS_NAME);
			Class<?> clazz=Class.forName(className);
			if(Collection.class.isAssignableFrom(clazz)){
				Collection<Object> dataList=(Collection<Object>)clazz.newInstance();
				JSONArray jsonArray=(JSONArray)dataObject;
				for (Iterator<Object> itr = jsonArray.iterator(); itr.hasNext();) {
					dataList.add(itr.next());
				}
				return dataList;
			}
		}else if(dataObject instanceof JSONObject){
			String className=jsonData.getString(CLASS_NAME);
			Class clazz=Class.forName(className);
			JSONObject jsonObject=(JSONObject)dataObject;
			return jsonObject.toJavaObject(clazz);
		}
		return dataObject;
	}

}
